﻿var SignalRContext = function () {
    this.messageHub = $.connection.messageHub;
    this.hubStart = function () {
        return $.connection.hub.start();
    };

    this.send = function (send) {
        return this.hubStart().done(send);
    };

    this.connection = function (userId) {
        this.send(function () {
            this.messageHub.server.connection(userId);
        }.bind(this));
    };

    this.sendData = function (data) {
        this.send(function () {
            this.messageHub.server.sendData(data);
        }.bind(this));
    };

    this.sendMessage = function (message) {
        this.send(function () {
            this.messageHub.server.sendMessage(message);
        }.bind(this));
    };

    this.sendDataToUser = function (userId, data) {
        this.send(function () {
            this.messageHub.server.sendDataToUser(userId, data);
        }.bind(this));
    };

    this.sendMessageToUser = function (userId, message) {
        this.send(function () {
            this.messageHub.server.sendMessageToUser(userId, message);
        }.bind(this));
    };

    this.receiveData = function (receiveData) {
        this.messageHub.client.receiveData = receiveData;
        this.hubStart();
    };

    this.receiveMessage = function (receiveMessage) {
        this.messageHub.client.receiveMessage = receiveMessage;
        this.hubStart();
    };

    $(window).on('beforeunload', function () {
        this.messageHub.server.disConnection();
    }.bind(this));
}

var sendMessage = function (toUserName, msgType, title, url, content) {
    $.post("/Home/AddMessage", {
        TO_USER_NAME: toUserName,
        MSG_TYPE: msgType,
        TITLE: title,
        URL: url,
        CONTENT: content,
    }, function (response) {
        if (response.code == 100) {
            var context = new SignalRContext();
            context.sendMessageToUser(toUserName,
            {
                code: "1100",
                title: title,
                url: url,
                content: content,
                data: {
                    id: response.data.MSG_ID
                }
            });
        }
    });
};